package com.rxyb.security.config;

import com.rxyb.security.constants.SecurityConstants;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @author YJH
 * @version 1.0
 * @description Feign 拦截器
 * @date 2020/5/21  17:32
 */
@Configuration
@Slf4j
public class FeignRequestInterceptor implements RequestInterceptor {


    @Override
    public void apply(RequestTemplate requestTemplate) {
        log.info("小子别想跑了 被我拦截了");
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes != null) {
            HttpServletRequest request = attributes.getRequest();
            // 如果请求头没有token，从url取出access_token
            final String header = request.getHeader(SecurityConstants.AUTHORIZATION);
            if (header == null) {
                //添加token
                final String token = request.getParameter(SecurityConstants.ACCESS_TOKEN);
                if (token != null) {
                    requestTemplate.header(SecurityConstants.AUTHORIZATION, String.format("%s %s", OAuth2AccessToken.BEARER_TYPE, token));
                }
            } else {
                // 如果请求头中有token，继续用requestTemplate传递
                if (header.startsWith(OAuth2AccessToken.BEARER_TYPE)) {
                    requestTemplate.header(SecurityConstants.AUTHORIZATION, header);
                }
            }
        }
    }
}
